from django.http import HttpResponse
from django.shortcuts import render, reverse
from myadmin import models
from myadmin.views import imgupload
import os
from django.core.paginator import Paginator


# Create your views here.

# 用户主页面
def index(request):
    # 获取会员内容,filter为空就all，所以也可以使用models.bookshop_users.objects.all()
    user_data = models.bookshop_users.objects.filter()

    # 接受 搜索的条件
    seletettype = request.GET.get('selecttype', None)
    seletetkey = request.GET.get('selectkey', None)


    if seletettype:
        # 有搜索条件
        if seletettype == 'all':
            pass
            # select * from users where name like '%a%' or price like '%a%'
            # user_data.filter(**serdata)是and关系，可以使用Q对象
            from django.db.models import Q
            user_data = user_data.filter(Q(phonenum__contains=seletetkey)|Q(sex__contains=seletetkey)|Q(nikename__contains=seletetkey))
        else:
            serdata = {f'{seletettype}__contains': seletetkey}
            user_data = user_data.filter(**serdata)
        # elif seletettype == 'nikename':
        #     user_data = user_data.filter(nikename__contains=seletetkey)
        # elif seletettype == 'sex':
        #     user_data = user_data.filter(sex__contains=seletetkey)

    # 会员内容分页
    # https://docs.djangoproject.com/en/4.0/topics/pagination/
    # 实例化分页对象，参数1：数据集；参数2：每页显示条数
    user_data_page_do = Paginator(user_data, 3)
    # 获取页码数，通过page参数，默认设置为1
    user_data_page_index = request.GET.get('page', 1)
    # 获取当前页的数据
    user_data_page_data = user_data_page_do.page(user_data_page_index)

    # 把数据(或者分页的数据)分配到模板页面中
    content = {'user_data': user_data_page_data}

    # 加载模板文件
    return render(request, 'myadmin/users/list.html', content)

# 用户添加页面
def adduser(request):
    # 如果方法是post，则接受表单数据，并提交；否则返回书籍添加页面。
    if request.method == 'POST':
        user_data = request.POST.dict()
        user_data.pop("csrfmiddlewaretoken")

        # 进行文件上传
        img_name = imgupload(request)
        if img_name:
            user_data['img_url'] = imgupload(request)
        else:
            user_data.pop('img_url')

        print(user_data)

        # 执行数据添加
        try:
            obj = models.bookshop_users(**user_data)
            obj.save()

            url = reverse(index)
            return HttpResponse('<script>alert("成功了");location.href="' + url + '";</script>')
        except:
            url = reverse(index)
            return HttpResponse('<script>alert("失败了");location.href="' + url + '";</script>')
    else:
        # 如果是GET请求
        return render(request, 'myadmin/users/add.html')

# 用户操作 修改页面
def edituser(request):
    id = request.GET.get('id')
    obj = models.bookshop_users.objects.get(id=id)
    return render(request, 'myadmin/users/edit.html', {'obj': obj})

# 用户修改 上传更新页面
def updateuser(request):
    user_data = request.POST.dict()
    user_data.pop("csrfmiddlewaretoken")

    # 判断更新，1 是否更新了图片
    file = request.FILES.get('img_url')
    if file:
        # 上传了图片
        filename = imgupload(request)
        # 删除原来的图片，需要页面中将img_url回传回来
        os.remove('.' + user_data['old_img_url'])
        user_data['img_url'] = filename
        # 删除老的图片信息
        user_data.pop('old_img_url')
    else:
        # 没有上传图片
        user_data['img_url'] = user_data['old_img_url']
        # 删除老的图片信息
        user_data.pop('old_img_url')

    # print(book_data)
    # 通过id来找到更新的位置，并完成更新操作
    try:
        models.bookshop_users.objects.filter(id=user_data['id']).update(**user_data)
        # return HttpResponse('更新成功')
        url = reverse(index)
        return HttpResponse('<script>alert("成功了");location.href="' + url + '";</script>')
    except:
        # return HttpResponse('更新失败')
        url = reverse(index)
        id = str(user_data['id'])
        return HttpResponse(f'<script>alert("失败了");location.href="{url}?id={id}";</script>')

# 删除用户
def deluser(request, id):
    try:
        # 通过id获取书籍对象
        obj = models.bookshop_users.objects.get(id=id)

        # 先删除图片
        # 图片在数据库中的url是 /static/upload/1638861833.8559818.jpg
        # 需要转换成 ./static/upload/1638861833.8559818.jpg
        os.remove('.' + obj.img_url)

        # 再删除数据
        obj.delete()
        info = "成功"
    except:
        info = "失败"
    url = reverse(index)
    return HttpResponse(f'<script>alert("{info}");location.href="' + url + '";</script>')

# 用户导入
def importuser(request):
    file_data = request.FILES.get()
    print(file_data)
    pass

